package net.sk.china.city.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Component
@Slf4j
public class JsonStrCovertUtil {
    private static ObjectMapper MAPPER;

    public JsonStrCovertUtil(ObjectMapper objectMapper) {
        MAPPER = objectMapper;
    }

    public static <T> List<T> strToObjArray(String jsonStr, Class<T> objClass){
        if (!StringUtils.hasText(jsonStr)) {
            throw new RuntimeException("内部处理JSON异常");
        }
        if (!(jsonStr.startsWith("[") && jsonStr.endsWith("]"))) {
            log.warn("此方法不能处理非数组的JSON字符串");
            throw new RuntimeException("内部处理JSON异常");
        }
        ArrayList<T> arrayList = null;
        try {
            JsonNode jsonNode = MAPPER.readTree(jsonStr);
            ObjectReader objectReader = MAPPER.readerForListOf(objClass);
            arrayList = new ArrayList<>();
            for (Iterator<JsonNode> it = jsonNode.elements(); it.hasNext(); ) {
                T t = objectReader.treeToValue(it.next(), objClass);
                arrayList.add(t);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return arrayList;
    }

    public static String objToStr(Object obj){
        if (obj == null) {
            return null;
        }
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
